import pageLifecycle, { pageLifecycleNames } from '@packages/face-runner/pageLifecycle';
import { execWxJob } from '@packages/lib-exec';
import os from '@packages/lib-os';
import * as libUrl from '@packages/lib-url';
import globalData from '@shared/globalData';

function handleD12Game() {
    if (WPT.curRouter.startsWith('/webApp/activity/2018d12/yuanbao')) {
        return {
            gameData: {
                type: 'double12_yuanbao',
            },
        };
    }

    if (WPT.curRouter.startsWith('/webApp/activity/2018d12/game/race')) {
        return {
            gameData: {
                type: 'double12_box',
            },
        };
    }
    return null;
}

/**
 * 分享成功上报
 */
function shareSuccessReport({ from, share }) {
    // 获取上报信息
    const instance = pageLifecycle.getPage();
    let shareData;
    if (instance && instance.getShareRepData) {
        shareData = instance.getShareRepData();
    }

    const shareTemplateMap = {
        'wechat-message': share.titleTemplate,
        'wechat-timeline': share.timelineTemplate,
        'wechat-qq': share.qqTemplate,
        'wechat-qzone': share.qqZoneTemplate,
    };

    if (pageLifecycle.getPage()) {
        pageLifecycle.emit({
            name: pageLifecycleNames.wechatShare,
            args: {
                success: true,
                from,
                share: {
                    shareTemplate: shareTemplateMap[from] || '',
                    ...share,
                },
            },
        });
    } else {
        const { showHideList = [] } = globalData.$curPage[0];
        showHideList.forEach((ins) => {
            ins.onWechatShare &&
                ins.onWechatShare({
                    success: true,
                    from,
                    share: {
                        shareTemplate: shareTemplateMap[from] || '',
                        ...share,
                    },
                });
        });
    }
}

/**
 * 通用方法 更改页面标题
 *
 * @param {String} title
 */
export function setTitle(title) {
    document.title = title || '金榜见';
    typeof window.wxx !== 'undefined' && window.wxx.title && window.wxx.title(document.title);
    os.isFullscreen && $(document).trigger('setTitleInNavigation', [title]);
}

/**
 * 通用方法 更改dom绑定的路由属性
 *
 * @param {String} title
 */
export function setPageProps(dom, props) {
    dom.info = props;
}

/**
 * 设置页面标题与分享
 * web runner 运行模式可用
 *
 * @export
 * @param {Object} html
 * @returns
 */
export function initHtml(html) {
    if (!html) {
        console.warn('html is empty');
        return;
    }

    // 更改title
    html.title && setTitle(html.title);
    if ($.isEmptyObject(html.share)) {
        return;
    }

    const { share } = html;
    const { location } = window;
    share.timeline = share.timeline || share.summary || share.title;
    share.imgUrl = share.imgUrl || `${globalData.WEI_HOST}res/img/logo256.jpg`;
    share.pics = share.pics || [];
    share.wbDesc = share.wbDesc || share.title;
    share.link = share.link || location.href;
    // 详情页
    share.shareType = share.uri ? 'card' : '';

    if (!libUrl.query(share.link).r) {
        share.link = libUrl.params(share.link, { r: 'shareTemplate', c: 'shareTemplate' });
    }

    share.link = libUrl.params(share.link, { sf: os.webType }); // 通过什么分享进入的标识

    // 分享前回调
    // 判断 faceRunner 生命周期中是否存在 Page 实例, 有则调用, 不存在则则表示是普通渲染模式
    if (pageLifecycle.getPage()) {
        pageLifecycle.emit({ name: pageLifecycleNames.beforeWechatShare, args: [share] });
    } else {
        // 兼容普通模式的回调
        const { showHideList = [] } = globalData.$curPage[0];
        // 分享前回调
        showHideList.forEach((ins) => {
            ins.onBeforeWechatShare && ins.onBeforeWechatShare(share);
        });
    }

    let appVersion = '';
    if (os.wpt && WPT.curRouter === '/uri/:uri@[0-9].*') {
        appVersion = `-${os.version.replace(/\./g, '')}`;
    }

    const formatLink = ({ originTemplate, originLink = 'link' }, from) => {
        const link = share[originTemplate]
            ? libUrl.params(share[originLink], {
                  r: `shareTemplate_${share[originTemplate]}${appVersion}`,
                  c: 'shareTemplate',
                  pos: `${share[originTemplate]}${appVersion}`,
                  sf: os.webType,
              })
            : share[originLink];

        return libUrl.params(link, from);
    };

    share.messageLink = formatLink(
        {
            originTemplate: 'titleTemplate',
        },
        { from: 'singlemessage' }
    );
    share.timelineLink = formatLink(
        {
            originTemplate: 'timelineTemplate',
        },
        {
            from: 'timeline',
        }
    );
    share.qqLink = formatLink({
        originTemplate: 'qqTemplate',
    });
    share.qqZoneLink = formatLink({
        originTemplate: 'qqZoneTemplate',
    });
    share.weiboLink = formatLink({
        originTemplate: 'wbDescTemplate',
    });
    // share.qLink = formatLink('qDescTemplate', 'qLink');

    const success = (channel) => {
        setTimeout(() => {
            $(document).trigger('wxShare:success', [{ from: channel, share }]);
        }, 200);

        shareSuccessReport({ from: channel, share });
    };
    const cancel = (channel) => {
        setTimeout(() => {
            $(document).trigger('wxShare:cancel', [{ from: channel, share }]);
        }, 20);
    };

    // APP内分享的数据不能有 success 属性
    window.wxShare = { ...share };
    window.wxShare.success = success;

    // 处理小程序分享
    if (window.__wxjs_environment === 'miniprogram') {
        // 保证不会多次触发？
        if (share.link + share.title != globalData.xcxShareKey) {
            globalData.xcxShareKey = share.link + share.title;
            const xcxShareData = {
                title: share.title,
                // xcxShareImg 用来设置小程序的分享图片，需要注意的是小程序的图片尺寸要比h5大
                imgUrl: share.xcxShareImg || share.imgUrl,
                link: share.link,
                href: window.location.href,
            };
            window.wx.miniProgram.postMessage({
                data: xcxShareData,
            });
        }
    } else {
        execWxJob(() => {
            if (window.wx && window.wx.ready) {
                window.wx.ready(() => {
                    if (!$.isEmptyObject(share.showMenuItems)) {
                        setTimeout(() => {
                            window.wx.hideOptionMenu();
                            window.wx.showMenuItems({
                                menuList: share.showMenuItems,
                            });
                        }, 1000);
                    } else {
                        WPT.showOptionMenu();
                    }
                    window.wx.onMenuShareAppMessage({
                        title: share.title,
                        desc: share.desc,
                        link: share.messageLink,
                        imgUrl: share.imgUrl,
                        success: () => {
                            success('wechat-message');
                        },
                        cancel: () => {
                            cancel('wechat-message');
                        },
                    });
                    window.wx.onMenuShareTimeline({
                        title: share.timeline,
                        desc: share.desc,
                        link: share.timelineLink,
                        imgUrl: share.imgUrl,
                        success: () => {
                            success('wechat-timeline');
                        },
                        cancel: () => {
                            cancel('wechat-timeline');
                        },
                    });
                    window.wx.onMenuShareQQ({
                        title: share.title,
                        desc: share.desc,
                        link: share.qqLink,
                        imgUrl: share.imgUrl,
                        success: () => {
                            success('wechat-qq');
                        },
                        cancel: () => {
                            cancel('wechat-qq');
                        },
                    });
                    window.wx.onMenuShareQZone({
                        // 失效
                        title: share.timeline,
                        desc: share.desc,
                        link: share.qqZoneLink,
                        imgUrl: share.imgUrl,
                        success: () => {
                            success('wechat-qzone');
                        },
                        cancel: () => {
                            cancel('wechat-qzone');
                        },
                    });
                });
            }
        });
    }
}

export function getHtmlInfoFromComponent(component) {
    if (!component) {
        return null;
    }

    const defaultHtml = component.constructor.html || {};

    if (component.state && component.state.html) {
        return {
            ...defaultHtml,
            ...component.state.html,
        };
    }

    return {
        ...defaultHtml,
        ...component.html,
    };
}

export function setPageTitle(instance) {
    if (!instance) {
        return;
    }

    const htmlInfo = getHtmlInfoFromComponent(instance);

    if (os.dyXcx) {
        htmlInfo.title = '微拍堂';
    }

    if (htmlInfo) {
        initHtml(htmlInfo);
    }
}
